package com.ujs.ucenter.controller;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.ujs.commonutils.constant.R;
import com.ujs.commonutils.utils.JwtUtils;
import com.ujs.servicebase.exception.GuliException;
import com.ujs.ucenter.entity.Member;
import com.ujs.ucenter.service.MemberService;
import com.ujs.ucenter.utils.ConstantWxUtils;
import com.ujs.ucenter.utils.HttpClientUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.URLEncoder;
import java.util.Map;

/**
 * @author zhangshihao
 * @create 2023-09-01 11:16
 */
@RequestMapping("/educenter/wx")
@Controller
@Api(tags = "微信接口")
public class WxApiController {
    @Autowired
    private MemberService memberService;

    @GetMapping("/callback")
    @ApiOperation("回调方法")
    public String callback(String code, String state) {
        try {
            // 1 获取code值，临时票据，类似于验证码
            // 2 拿着code请求 微信固定的地址，得到两个值 accsess_token 和 openid
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";
            // 拼接三个参数 ：id  秘钥 和 code值
            String accessTokenUrl = String.format(
                    baseAccessTokenUrl,
                    ConstantWxUtils.WX_OPEN_APP_ID,
                    ConstantWxUtils.WX_OPEN_APP_SECRET,
                    code
            );
            // 请求拼接好的地址，得到两个返回值access_token 和 openid
            // 使用httpClient发送请求，得到返回结果
            // {"access_token":"72_UelV7AU5L1dxYRhsyHK0LJNG2UNrho8tokijSpGCMvkl8O_9lCh_JCXmJh4L6AFnpId9VBN6zM872mVwNi2dvAmdWoq_om27PNYiR07rh9Q",
            // "expires_in":7200,
            // "refresh_token":"72_D_mdJSFicl03L3wACiSajPwjs9ILg9qFbTQeiXTypzQ44LjFX05AKe8qiN-VyrF8GIJXuVDxsdfEj-SAjZaarer_F5SL3ti4ATsCA1bH5ZY",
            // "openid":"o3_SC51MFAoA72s2iaN4QQq_EUCw",
            // "scope":"snsapi_login",
            // "unionid":"oWgGz1IRdKDcYhMrrSlgn7z5F3uM"}
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);

            //从accessTokenInfo字符串获取出来两个值 accsess_token 和 openid
            //把accessTokenInfo字符串转换map集合，根据map里面key获取对应值
            //使用json转换工具 Gson
            Map mapAccessToken = JSON.parseObject(accessTokenInfo, Map.class);
            // Map mapAccessToken = new Gson().fromJson(accessTokenInfo, Map.class);
            String access_token = (String)mapAccessToken.get("access_token");
            String openid = (String)mapAccessToken.get("openid");
            // System.out.println("access_token="+access_token+" openid="+openid);

            // 扫码人信息添加到数据库
            // 判断数据库是否存在相同的用户信息，根据openid判断
            Member member = memberService.getOpenIdMember(openid);
            if (member == null) {
                // 3.表中没有相同的数据，添加
                // 拿着得到accsess_token 和 openid，再去请求微信提供固定的地址，获取到扫描人信息
                // 访问微信的资源服务器，获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);
                String userInfo = HttpClientUtils.get(userInfoUrl);
                Map userInfoMap = new Gson().fromJson(userInfo, Map.class);
                String nickname = (String)userInfoMap.get("nickname"); // 昵称
                String headimgurl = (String)userInfoMap.get("headimgurl"); // 头像

                member = new Member();
                member.setOpenid(openid);
                member.setNickname(nickname);
                member.setAvatar(headimgurl);
                memberService.save(member);
            }

            // 使用jwt生成token字符串
            String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
            // 登录成功，跳转页面
            return "redirect:http://localhost:3000?token=" + jwtToken;
        } catch (Exception e) {
            throw new GuliException(20001, "扫码登录失败");
        }
    }

    @GetMapping("/login")
    @ResponseBody
    @ApiOperation("生成二维码")
    public R getQrCode() {
        // 1 获取code值，临时票据，类似于验证码
        // 2 拿着code请求 微信固定的地址，得到两个值 accsess_token 和 openid
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "wechat_redirect";
        String redirectUrl = ConstantWxUtils.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "utf-8");
            System.out.println(redirectUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 拼接三个参数 ：id  秘钥 和 code值
        String url = String.format(
                baseUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                redirectUrl, // http%3A%2F%2Fguli.shop%2Fapi%2Fucenter%2Fwx%2Fcallback
                "ujs"
        );
        return R.ok().data("url", url);
    }
}
